<?php

namespace App\Http\Middleware;
use Auth;
use JWTAuth;
use Closure;
use Mockery\Exception;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class TokenCheck extends BaseMiddleware
{
    /**
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            if (!$this->auth->parseToken()->authenticate()) {  //获取到用户数据，并赋值给$user
                return response()->json([
                    'code' => 1004,
                    'msg' => '找不到用户'
                ],400);
            }
            //如果想向控制器里传入用户信息，将数据添加到$request里面
            //$request->attributes->add($user);//添加参数
            return $next($request);

        } catch (TokenExpiredException $e) {
            try {
                    //刷新用户的 token
                    $token = $this->auth->refresh();
                    //使用一次性登录以保证此次请求的成功
                    Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
            } catch (JWTException $exception) {
                // 如果捕获到此异常,即代表 refresh 也过期了,用户无法刷新令牌，需要重新登录。
                return response()->json([
                    'code' => 1003,
                    'msg' => 'token失效,请重新登录',
                ],401);

            }
            return $this->setAuthenticationHeader($next($request), $token);
        } catch (TokenInvalidException $e) {
            return response()->json([
                'code' => 1002,
                'msg' => 'token无效',  //token无效
            ],401);
        } catch (JWTException $e) {
            return response()->json([
                'code' => 1001,
                'msg' => 'token为空' , //token为空
            ],401);
        }
    }
}
